package com.sunwayworld.basemodule.coredata.method.service.impl;

import com.sunwayworld.basemodule.coredata.method.bean.LimsMethodBean;
import com.sunwayworld.basemodule.coredata.method.bean.LimsMethodVersionBean;
import com.sunwayworld.basemodule.coredata.method.dao.LimsMethodVersionDao;
import com.sunwayworld.basemodule.coredata.method.service.LimsMethodService;
import com.sunwayworld.basemodule.coredata.method.service.LimsMethodVersionService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
@GikamBean
public class LimsMethodVersionServiceImpl implements LimsMethodVersionService {

    @Autowired
    private LimsMethodVersionDao limsMethodVersionDao;

    @Autowired
    @Lazy
    private LimsMethodService methodService;

    @Override
    @SuppressWarnings("unchecked")
    public LimsMethodVersionDao getDao() {
        return limsMethodVersionDao;
    }

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsMethodVersionBean methodVersionBean = jsonWrapper.parseUnique(LimsMethodVersionBean.class);
        methodVersionBean.setId(ApplicationContextHelper.getNextSequenceNumber(getDao().getTable()));
        LimsMethodBean methodBean = methodService.getDao().selectById(methodVersionBean.getMethodId());
        Integer version = getDao().selectMaxVersion(methodVersionBean.getMethodId());
        methodVersionBean.setMethodCode(methodBean.getMethodCode());
        methodVersionBean.setMethodVersion(version == null ? "1" : String.valueOf(version));
        getDao().insert(methodVersionBean);
        return methodVersionBean.getId();
    }

}
